using System;
using System.Linq;
using ExtendedMvc.Common.Diagnostics;
//using ExtendedMvc.Behaviors;
using ExtendedMvc.Html;

namespace ExtendedMvc.Elements {
	/// <summary>
	/// Base class for HTML elements.
	/// </summary>
	/// <typeparam name="T">The derived class type.</typeparam>
	public abstract class TableElement<T> : Element<T> where T : TableElement<T> {
		private string _onClick;
		private string _onMouseOut;
		private string _onMouseOver;

		protected TableElement(string tag, string id = null)
			: base(tag, id) {
			Check.Argument.IsNotValid(tag, "tag", t => HtmlTableTag.Values.Contains(t));
		}

		/// <summary>
		/// Add a value to the 'class' attribute.
		/// </summary>
		/// <param name="classToAdd">The value of the class to add.</param>
		public virtual T CssClass(string value) {
			if (!string.IsNullOrEmpty(value)) Builder.AddCssClass(value);
			return (T)this;
		}

		/// <summary>
		/// Set the 'title' attribute.
		/// </summary>
		/// <param name="value">The value of the 'title' attribute.</param>
		public virtual T Title(string value) {
			if (!string.IsNullOrEmpty(value)) SetAttribute(HtmlAttribute.Title, value);
			return (T)this;
		}

		/// <summary>
		/// Set the 'style' attribute.
		/// </summary>
		/// <param name="values">A list of funcs, each epxressing a style name value pair.  Replace dashes with 
		/// underscores in style names. For example 'margin-top:10px;' is expressed as 'margin_top => "10px"'.</param>
		public virtual T Styles(params Func<string, string>[] values) {
			var styles = values.Aggregate(string.Empty, (a, b) => a + (a == string.Empty ? "" : " ") + string.Format("{0}:{1};", b.Method.GetParameters()[0].Name.Replace('_', '-'), b(null)));
			if (!string.IsNullOrEmpty(styles)) MergeAttribute(HtmlAttribute.Style, styles);
			return (T)this;
		}

		#region Events
		public virtual T OnClick(string value) {
			_onClick = value;
			return (T)this;
		}

		public virtual T OnMouseOut(string value) {
			_onMouseOut = value;
			return (T)this;
		}

		public virtual T OnMouseOver(string value) {
			_onMouseOver = value;
			return (T)this;
		}
		#endregion

		protected override void Prepare() {
			if (!string.IsNullOrWhiteSpace(_onClick)) SetAttribute(HtmlEventAttribute.OnClick, _onClick);
			if (!string.IsNullOrWhiteSpace(_onMouseOut)) SetAttribute(HtmlEventAttribute.OnMouseOut, _onMouseOut);
			if (!string.IsNullOrWhiteSpace(_onMouseOver)) SetAttribute(HtmlEventAttribute.OnMouseOver, _onMouseOver);
			base.Prepare();
		}

	}
}